package dang.dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import dang.dao.CategoryDao;
import dang.entity.Category;
import dang.exception.DangException;

public class CategoryDaoImpl extends DangDaoImpl implements CategoryDao {

	@Override
	public List<Category> findAll() throws DangException {
		String hql="from Category";
		Session s = getSession();
		List<Category> cats=s.createQuery(hql).list();
		return cats;
	}

	@Override
	public List<Category> findByParentId(int parentId) throws DangException  {
		String hql=" select c ,count(products) as pnum from Category c left outer join  c.products products " +
		" where  c.parent_id=? group by c.id";
		Session s =getSession();
		Query query=s.createQuery(hql);
		query.setParameter(0, parentId);
		Iterator<Object> pairs=query.iterate();
		List<Category> categories=new ArrayList<Category>();
		while (pairs.hasNext()) {
			Object[] os = (Object[]) pairs.next();
			Category c =(Category) os[0];
			int pnum=(int)((Long)os[1]+0);
			c.setPnum(pnum);
			categories.add(c);
		}
		return categories;		
		
	}

	@Override
	public String findById(int id) throws DangException  {
		String hql = "select name from Category  c where c.id =? ";
		Session s =getSession();
		Query query=s.createQuery(hql);
		query.setParameter(0, id);
		String name=(String)query.uniqueResult();
		return name;
	}
}
